<?php

namespace app\health\controller;

use app\health\model\HealthActivity;
use app\health\model\HealthActivityRecord;
use app\health\model\HealthCoupon;
use app\health\model\HealthUser;
use app\health\model\HealthUserAccount;
use app\health\service\EquityCenterService;
use Exception;
use think\Db;

class Activity extends ApiBase
{

    protected $noNeedLogin = ['starterPack'];

    /**
     * 新用户弹框礼包
     * @return void
     * @Author 张旭鹏
     * @DateTime 2023-06-16
     */
    public function starterPack()
    {
        $activity = HealthActivity::where('type', 1)->where('status', 1)->find();
        $isShow   = $activity ? 1 : 0;
        $content  = []; //活动内容
        if ($activity) {
            // 活动规则
            $activityRule = json_decode($activity->rule, true) ?: [];
            $content      = json_decode($activity->content, true);
            if ($this->auth->id) {
                // 活动记录
                $activityRecord = HealthActivityRecord::where('activity_id', $activity->id)->where('user_id', $this->auth->id)->find();
                if (!$activityRecord) {
                    $activityRecord = HealthActivityRecord::create([
                        'activity_id' => $activity->id,
                        'user_id'     => $this->auth->id,
                        'is_receive'  => 0,
                        'remind_num'  => 0
                    ]);
                }
                if ($activityRecord->is_receive == 1 || !empty($activityRule['remind']) && $activityRecord['remind_num'] > $activityRule['remind']) {
                    $isShow = 0;
                }
                if ($isShow == 1) {
                    $activityRecord->setInc('remind_num');
                }
            }
        }
        $this->success('', [
            'is_show' => $isShow,
            'content' => $content
        ]);
    }

    /**
     * 新用户弹框礼包领取
     * @Author 张旭鹏
     * @DateTime 2023-06-16
     */
    public function receiveStarterPack()
    {
        try {
            Db::startTrans();
            $activity = HealthActivity::where('type', 1)->where('status', 1)->find();
            if (!$activity) {
                throw new Exception('活动未开启');
            }
            $activityRecord = HealthActivityRecord::where('activity_id', $activity->id)
                ->where('user_id', $this->auth->id)
                ->lock(true)
                ->find();
            if ($activityRecord && $activityRecord['is_receive'] == 1) {
                throw new Exception('礼包已领取');
            }
            $type = $this->request->param('type');
            if (!$type) {
                throw new Exception('请选择礼包选项');
            }
            $content      = json_decode($activity->content, true) ?: [];
            $activityItem = [];
            foreach ($content as $item) {
                if ($item['type'] == $type) {
                    $activityItem = $item;
                    break;
                }
            }
            if (empty($activityItem)) {
                throw new Exception('礼包不存在');
            }
            if (EquityCenterService::isPajkVip($this->auth->mobile) == 0) {
                throw new Exception('请先订购业务');
            }
            $successMsg = '领取成功';
            if ($activityItem['type'] == 1) {
                $reward  = explode('-', $activityItem['reward']);
                $balance = 0;
                if (count($reward) === 2) {
                    $balance = bcdiv(mt_rand(bcmul($reward[0], 10), bcmul($reward[1], 10)), '10', 1);
                } elseif (count($reward) === 1) {
                    $balance = $reward[0];
                }
                HealthUser::where('id', $this->auth->id)->setInc('balance', $balance);
                HealthUserAccount::income(
                    $this->auth->id,
                    HealthUserAccount::FORM_TYPE_ACTIVITY,
                    HealthUserAccount::ACCOUNT_TYPE_BALANCE,
                    $balance,
                    '新手活动礼包领取'
                );
                $successMsg = '领取成功，请到我的红包查看';
            }
            if ($activityItem['type'] == 2) {
                //优惠券领取
                HealthCoupon::receive($activityItem['reward'], $this->auth->id);
                $successMsg = '领取成功，请到我的优惠券查看';
            }
            $activityRecord->is_receive = 1;
            $activityRecord->save();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success($successMsg);
    }
}
